package rs.udd.web.binding;

import java.beans.PropertyEditorSupport;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Service;

@Service
public class DateBinder extends PropertyEditorSupport {

	private static final Logger LOG = LogManager.getLogger(DateBinder.class);

//	 private static SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy");
	private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

	@Override
	public void setAsText(String text) {
		if (StringUtils.isBlank(text)) {
			setValue(null);
			return;
		}
		Date date;
		try {
			date = sdf.parse(text);
		} catch (ParseException e) {
			LOG.error(e);
			date = null;
		}
		setValue(date);
	}

	@Override
	public String getAsText() {
		Date date = (Date) getValue();
		if (date == null)
			return "";
		return sdf.format(date);
	}

}
